import React, { Component } from 'react';
import styles from './index.module.scss';
import { withRouter } from 'next/router';
import { withTranslation } from 'next-i18next';
import { motion } from 'framer-motion';
import { connect } from 'react-redux';
import { update } from '@/utils/immutableUtil';
import ConfirmationDialog from '@/components/basicComp/CloseDialog';
import { delPlugin } from '@/api/plugins';

@withTranslation('common')
@withRouter
@connect(({ }) => ({}))
class Comp extends Component {
  state = {
    list: [],
    open: false, // 是否打开删除确认弹窗
    delServerName: '',//删除接口 需要的
  };
  shouldComponentUpdate = (np, ns) => update.call(this, np, ns);
  constructor(props) {
    super(props);
    this.state = {
      activeTab: 'discover',
      searchQuery: '',
      activeCategory: 'all',
      isLoading: false,
      list: [],
      open: false,
      delServerName: '',
    };
  }

  handleInstall = async (plugin) => {
    let newEnv = Object.keys(plugin?.env).map((item => {
      return { key: item, isRequired: true, value: null }
    }))
    let newPlugin = { ...plugin };
    newPlugin.newEnv = newEnv;
    let newArgs = plugin?.args.map(item => {
      return { isRequired: true, value: item }
    })
    newPlugin.newArgs = newArgs;
    newPlugin.isEdit = false; // 是否是编辑状态
    // 打开弹窗
    this.props?.openAddCustomPlugin(newPlugin);
    this.props?.changeModalTitle('Install Plugin'); // 设置弹窗标题
    this.props?.changParentState({
      pluginModalTitle: 'Install Plugin',
      pluginModalType: 'install',
    }); // 设置弹窗类型
  };

  getPluginIcon = (name) => {
    // Simple function to return an icon based on plugin name
    // In a real implementation, you might use actual icons
    // const firstLetter = name.charAt(0).toUpperCase();
    return <div className={styles.pluginIcon}><img src={this.props?.getImg(name)} /></div>
    // return <div className={styles.pluginIcon}>{firstLetter}</div>;
  };


  // 点击打开删除确认弹窗
  handleConfirmatIsOpen = () => {
    this.setState({
      open: !this.state.open
    })
  }


  // 删除
  handleDelPlugin = async (params) => {
    const { delServerName } = this.state;
    let rs = await delPlugin({ server_name: delServerName });
    if (rs.data?.code == 200) {
      //调用 列表接口
      this.props?.getDiscoverList();
      this.handleConfirmatIsOpen(); // 关闭弹窗
    } else {
      toast.error(rs?.data?.sub_message);
    }
  }


  render() {
    const { discoverList } = this.props;
    const { open } = this.state;
    return (
      <motion.div
        initial={{ opacity: 0 }} // 初始状态：不透明度为 0
        animate={{ opacity: 1 }} // 动画状态：不透明度为 1
        transition={{ duration: 0.5 }} // 动画持续时间为 1 秒
        style={{ height: '100%' }}
      >
        <div value={this.controller}>
          <div className={styles.container}>
            {/* Plugins Grid */}
            <div className={styles.pluginsGrid}>
              {discoverList?.map((plugin, index) => (
                <div
                  key={`${plugin.server_name}-${index}`}
                  className={styles.pluginCard}
                  onClick={(e) => {
                    // 防止点击状态按钮时触发卡片点击事件
                    if (e.target.closest('button')) {
                      return;
                    }
                    // 点击打开 plugin详情
                    // openPluginDetails && openPluginDetails(plugin);
                  }}
                >
                  <div className={styles.pluginContent}>
                    {this.getPluginIcon(plugin.server_name)}
                    <div className={styles.pluginInfo}>
                      <div className={styles.pluginName}>{plugin?.server_name}</div>
                      <div className={styles.pluginNamespace}>
                        {plugin?.server_description}
                      </div>
                    </div>
                  </div>

                  <div className={styles.status}>
                    <span className={styles.statusText}>•••</span>
                    {/*展示弹窗  */}
                    <div className={styles.dropDown}>
                      <div className={styles.dropDownItem} onClick={() => this.handleInstall(plugin)}>
                        <i className='iconfont icon-xiazai'></i>
                        <span>Install</span>
                      </div>
                      <div className={styles.dropDownItem} onClick={() => {
                        console.log('plugin del: ', plugin);
                        this.setState({
                          delServerName: plugin.server_name
                        }, () => {
                          this.handleConfirmatIsOpen();
                        })
                      }}>
                        <i className='iconfont icon-Delete'></i>
                        <span>Delete</span>
                      </div>
                    </div>
                  </div>
                </div>
              ))}
            </div>
          </div>

          {/* 删除确认框 */}
          <ConfirmationDialog
            open={open}
            onOpenChange={this.handleConfirmatIsOpen}
            onConfirm={this.handleDelPlugin}
            title='Delete Plugin'
            description='Are you sure you want to delete this plugin? This cannot be undone.'
          />
        </div>
      </motion.div>
    );
  }
}

export default Comp;
